import { app, ipcMain } from 'electron'
import { chromium } from 'playwright'
import path from 'node:path'
import fs from 'fs'

export function browserServiceInit(window: Electron.BrowserWindow){
  win = window
  ipcMain.handle('open-browser', async (_, url, isLogin = false, id = 0, callbackUrl = '') => {
    return await openBrowser(url, isLogin, id, callbackUrl)
  })
  ipcMain.handle('close-browser', async () => {
    return await closeBrowser()
  })
  ipcMain.handle('save-cookies', async (_, cookies, id) => {
    return await saveCookies(cookies, id)
  })
  ipcMain.handle('load-cookies', async (_, id) => {
    return await loadCookies(id)
  })
  ipcMain.handle('clear-cookies', async (_, id) => {
    return await clearCookies(id)
  })
}

// 全局变量
let win: Electron.BrowserWindow | null = null
let browser: any = null
let page: any = null

// 获取cookie路径
function getCookiePath(id: string | number) {
  const cookiesDir = path.join(app.getPath('userData'), 'cookies/' + id)
  const cookiesPath = path.join(cookiesDir, 'cookies.json')
  return { cookiesDir, cookiesPath }
}

// 关闭浏览器和页面
async function closeResources() {
  if (page) {
    await page.close()
    page = null
  }
  if (browser) {
    await browser.close()
    browser = null
  }
}

// 打开浏览器
async function openBrowser(url: string, isLogin = false, id = 0, callbackUrl = '') {
  try {
    if (!browser) {
      browser = await chromium.launch({
        headless: false, // 显示浏览器界面
        args: [
          '--disable-blink-features=AutomationControlled',
          '--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"'
        ]
      })
      // 监听浏览器关闭事件
      browser.on('disconnected', () => {
        browser = null
        page = null
      })
    }
    if (!page) {
      page = await browser.newPage()
      // 监听页面关闭事件
      page.on('close', () => {
        page = null
      })
    }

    if (isLogin) {
      await page.goto(url)
      Promise.race([
        page.waitForURL(callbackUrl),
        // page.waitForSelector('.csdn-profile-nickName')
      ]).then(async() => {
        // 登录成功，自动获取cookie并保存，然后关闭浏览器
        const cookies = await page.context().cookies()
        await saveCookies(cookies, id)
        // 发送集成成功的事件通知UI更新状态
        win?.webContents.send('website-integrated', {id})
        await closeResources()
      }).catch((e: any) => {
        console.error('login error', e)
      });
    } else {
      try {
        const result = await loadCookies(id)
        if (result.success) {
          await page.context().addCookies(result.cookies)
          await page.goto(url)
        }
      } catch(e: any) {
        await closeResources()
        console.error('load cookies error', e)
      }
    }
    return { success: true }
  } catch (error: any) {
    return { success: false, error: error?.message || '未知错误' }
  }
}

// 关闭浏览器
async function closeBrowser() {
  try {
    await closeResources()
    return { success: true }
  } catch (error: any) {
    return { success: false, error: error?.message || '未知错误' }
  }
}

// 保存cookie到文件
async function saveCookies(cookies: any, id: string | number) {
  try {
    const { cookiesDir, cookiesPath } = getCookiePath(id)
    
    // 确保目录存在
    await fs.promises.mkdir(cookiesDir, { recursive: true })
    
    await fs.promises.writeFile(cookiesPath, JSON.stringify(cookies, null, 2))
    return { success: true }
  } catch (error: any) {
    return { success: false, error: error?.message || '保存cookie失败' }
  }
}

// 从文件加载cookie
async function loadCookies(id: string | number) {
  try {
    const { cookiesPath } = getCookiePath(id)
    const data = await fs.promises.readFile(cookiesPath, 'utf-8')
    const cookies = JSON.parse(data)
    return { success: true, cookies }
  } catch (error: any) {
    return { success: false, error: error?.message || '加载cookie失败' }
  }
}

// 清除本地保存的cookie
async function clearCookies(id: string | number) {
  try {
    const { cookiesPath } = getCookiePath(id)
    await fs.promises.unlink(cookiesPath)
    return { success: true }
  } catch (error: any) {
    // 如果文件不存在，也认为是成功的
    if (error.code === 'ENOENT') {
      return { success: true }
    }
    return { success: false, error: error?.message || '清除cookie失败' }
  }
} 